<?php

/**
 * This is the model class for table "posts".
 * @property int $post_id
 * @property int $user_id 
 * @property string $title
 * @property string $content
 * @property date $time_created
 * @property int $total_comment
 * @property string $attachment 
 * @property int $status 
 * @property string $tags 
 * @property int $post_type
 * @property int $is_private  
 */
class Posts extends CActiveRecord {

    const IS_PRIVATE = 1;
    const IS_PUBLIC = 0;
    const TOTAL_RECORD = 30;
    const STATUS_APPROVE = 1;
    const STATUS_PENDING = 0;
    const TYPE_TEXT = 0;
    const TYPE_PHOTO = 1;
    const TYPE_AUDIO = 2;
    const TYPE_VIDEO = 3;

    //addition attributes    
    public $userName;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{posts}}';
    }

    public function relations() {
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'user_id'),
	    'comment' => array(self::HAS_MANY, 'Comment', 'post_id')
	);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	return array(
	    array('title, content', 'required'),
	    array('post_type, user_id, is_private, post_id, total_comment, time_created, attachment, tags, userName', 'safe')
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'title' => 'Title',
	    'content' => 'Description',
	    'is_private' => 'Public/Private',
	    'tags' => 'Tags'
	);
    }

    /*
     * 
     */

    public function beforeSave() {
	parent::beforeSave();
	$this->time_created = date('Y-m-d', time());

	return TRUE;
    }

    public function afterSave() {
	parent::afterSave();
    }

    /**
     * After delete post
     */
    public function afterDelete() {
	parent::afterDelete();

	////delete img
	$aAttachment = unserialize($this->attachment);
	if (isset($aAttachment['photo']) && $aAttachment['photo']) {
	    //delete old file
	    foreach ($aAttachment['photo'] as $img) {
		deleteFile(UPLOAD_PATH . 'photo/' . $img);
	    }
	}

	if (isset($aAttachment['audio']) && $aAttachment['audio']) {
	    deleteFile(UPLOAD_PATH . 'audio/' . $aAttachment['audio']);
	}

	if (isset($aAttachment['video']) && $aAttachment['video']) {
	    deleteFile(UPLOAD_PATH . 'video/' . $aAttachment['video']);
	}

	////delete comment
	db()->createCommand('DELETE FROM {{comments}} WHERE post_id = ' . $this->post_id);

	////delete like
//	db()->createCommand('DELETE FROM {{likes}} WHERE post_id = ' . $this->post_id . ' and type_id = "post"');
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($id = '') {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.
	$criteria = new CDbCriteria;
	$criteria->with = 'user';
	if ($id) {
	    $criteria->addCondition('t.user_id=' . $id);
	}
	$criteria->compare('post_id', $this->post_id, true);
	$criteria->compare('title', $this->title, true);
	$criteria->compare('post_type', $this->post_type, true);
	$criteria->compare('user.username', $this->userName, true);
	$criteria->compare('post_type', $this->post_type, true);

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    ),
	    'sort' => array(
		'defaultOrder' => array(
		    'time_created' => CSort::SORT_DESC
		),
	    )
	));
    }

    /*
     * get type of post to display some thing( image, name)
     */

    public function getType() {
	switch ($this->post_type) {

	    case Posts::TYPE_PHOTO:
		$img = "<img class='img-type-post' src='" . WWW_URL . "images/option-photo-icon.png'/>";
		break;
	    case Posts::TYPE_AUDIO:
		$img = "<img class='img-type-post' src='" . WWW_URL . "images/option-audio-icon.png'/>";
		break;
	    case Posts::TYPE_VIDEO:
		$img = "<img class='img-type-post' src='" . WWW_URL . "images/option-video-icon.png'/>";
		break;
	    case Posts::TYPE_TEXT:default:
		$img = "<img class='img-type-post' src='" . WWW_URL . "images/option-text-icon.png'/>";
		break;
	}
	return $img;
    }

    /*
     * get list type of post
     */

    public static function getListType() {
	return array(
	    '' => 'All',
	    self::TYPE_TEXT => 'Text',
	    self::TYPE_PHOTO => 'Photo',
	    self::TYPE_AUDIO => 'Audio',
	    self::TYPE_VIDEO => 'Video'
	);
    }

    /*
     * get img url
     */

    public function getImgUrl($size = 'thumb') {
	switch ($size) {
	    case 'thumb' :
		$width = 200;
		$height = 150;
		break;
	    case 'small' :
		$width = 64;
		$height = 64;
		break;
	    default :
		$width = 800;
		$height = 600;
		break;
	}

	$attachment = unserialize($this->attachment);
	$img = array();
	if (isset($attachment['photo']) && $attachment['photo']) {
	    foreach ($attachment['photo'] as $photo) {
		$img[] = ImageHelper::thumb($width, $height, 'photo' . DIRECTORY_SEPARATOR . $photo);
	    }
	}
	return $img;
    }

    /*
     * get audio
     */

    public function getAudio() {
	$attachment = unserialize($this->attachment);
	if (isset($attachment['audio']) && $attachment['audio']) {
	    $audio = '<audio width="500" controls>
	    			<source src="' . UPLOAD_URL . 'audio/' . $attachment['audio'] . '" type="audio/ogg">
	    			<source src="' . UPLOAD_URL . 'audio/' . $attachment['audio'] . '" type="audio/mpeg">
	    			Your browser does not support the audio element.
	    		    </audio>';
	} else {
	    $audio = '';
	}
	return $audio;
    }

    /*
     * get video
     */

    public function getVideo() {
	$attachment = unserialize($this->attachment);
	if (isset($attachment['video']['upload']) && $attachment['video']['upload']) {
	    $video = ' <video width="500" height="400" poster="poster.jpg" controls="controls" preload="none">
	    			<!-- MP4 for Safari, IE9, iPhone, iPad, Android, and Windows Phone 7 -->
	    			<source type="video/mp4" src="' . UPLOAD_URL . 'video/' . $attachment['video']['upload'] . '" />
	    			<!-- WebM/VP8 for Firefox4, Opera, and Chrome -->
	    			<source type="video/webm" src="' . UPLOAD_URL . 'video/' . $attachment['video']['upload'] . '" />
	    			<!-- Ogg/Vorbis for older Firefox and Opera versions -->
	    			<source type="video/ogg" src="' . UPLOAD_URL . 'video/' . $attachment['video']['upload'] . '" />
	    			<!-- Optional: Add subtitles for each language -->
	    			<track kind="subtitles" src="subtitles.srt" srclang="en" />
	    			<!-- Optional: Add chapters -->
	    			<track kind="chapters" src="chapters.srt" srclang="en" /> 
	    			<!-- Flash fallback for non-HTML5 browsers without JavaScript -->
	    			<object width="320" height="240" type="application/x-shockwave-flash" data="flashmediaelement.swf">
	    			    <param name="movie" value="flashmediaelement.swf" />
	    			    <param name="flashvars" value="controls=true&file=' . UPLOAD_URL . 'video/' . $attachment['video']['upload'] . '" />
	    			    <!-- Image as a last resort -->
	    			    <img src="" width="320" height="240" title="No video playback capabilities" />
	    			</object>
	    		    </video>';
	} else {
	    $video = '';
	}
	return $video;
    }

    public function getTitle() {
	return "<a href='" . SITE_NAME_URL . "post/" . $this->post_id . "'>" . $this->title . "</a>";
    }

}

